import React, { useEffect, useState } from "react";
import "./user.css";
import {
  Button,
  Form,
  Input,
  Table,
  Popconfirm,
  Modal,
  InputNumber,
  Select,
  DatePicker,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { getUser, addUser, editUser, deleteUser } from "../../api";
import dayjs from "dayjs";
const User = () => {
  const handleClick = (type, row) => {
    if (type === "add") setModalType(0);
    else {
      setModalType(1);
      const cloneData = JSON.parse(JSON.stringify(row));
      cloneData.birth = dayjs(cloneData.birth);
      form.setFieldsValue(cloneData);
    }
    setIsModalOpen(true);
  };
  const handleSearch = ({ name }) => {
    setSearchObj({ name });
  };
  const handleDelete = ({ id }) => {
    deleteUser({ id }).then(() => getTableData());
  };
  const [searchObj, setSearchObj] = useState({ name: "" });
  const [userList, setUserList] = useState([]);
  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
    },
    {
      title: "性别",
      dataIndex: "sex",
      render: (text) => (text ? "男" : "女"),
    },
    {
      title: "年龄",
      dataIndex: "age",
    },
    {
      title: "生日",
      dataIndex: "birth",
    },
    {
      title: "地址",
      dataIndex: "addr",
    },
    {
      title: "操作",
      render: (row) => {
        return (
          <div>
            <Button
              type="primary"
              size="small"
              onClick={() => handleClick("edit", row)}
              style={{ marginRight: "10px" }}
            >
              编辑
            </Button>
            <Popconfirm
              title="提示"
              description="此操作将删除该用户, 是否继续?"
              okText="确认"
              cancelText="取消"
              onConfirm={() => handleDelete(row)}
            >
              <Button type="primary" danger size="small">
                删除
              </Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];
  const getTableData = () => {
    getUser(searchObj).then(({ data }) => {
      setUserList(data.list);
    });
  };

  useEffect(() => {
    getTableData();
  }, [searchObj]);

  // 0（新增）1（编辑）
  const [modalType, setModalType] = useState(0);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const handleOk = () => {
    form.validateFields().then((values) => {
      values.birth = dayjs(values.birth).format("YYYY-MM-DD");
      if (modalType) {
        editUser(values);
      } else {
        addUser(values);
      }
      handleCancel();
      getTableData();
    });
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
  };
  const onModalFinish = (values) => {};
  const { TextArea } = Input;
  const [form] = Form.useForm();
  return (
    <div className="user">
      <div className="flex-box space-between">
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => handleClick("add")}
        >
          新增
        </Button>
        <Form onFinish={handleSearch} layout="inline">
          <Form.Item name="name">
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Table
        columns={columns}
        dataSource={userList}
        rowKey="id"
        size="middle"
        style={{ marginTop: "20px" }}
      />
      <Modal
        title={(modalType ? "编辑" : "新增") + "用户"}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          onFinish={onModalFinish}
          labelCol={{ span: 4 }}
          labelAlign="left"
          wrapperCol={{ span: 20 }}
        >
          {modalType == 1 && (
            <Form.Item name="id" hidden>
              <Input />
            </Form.Item>
          )}
          <Form.Item label="姓名" name="name" rules={[{ required: true }]}>
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item label="性别" name="sex" rules={[{ required: true }]}>
            <Select
              options={[
                {
                  value: 0,
                  label: "女",
                },
                {
                  value: 1,
                  label: "男",
                },
              ]}
              placeholder="请选择性别"
            />
          </Form.Item>
          <Form.Item label="年龄" name="age" rules={[{ required: true }]}>
            <InputNumber placeholder="请输入年龄" min={0} max={120} />
          </Form.Item>
          <Form.Item label="生日" name="birth" rules={[{ required: true }]}>
            <DatePicker placeholder="请选择生日" format={"YYYY/MM/DD"} />
          </Form.Item>
          <Form.Item label="地址" name="addr" rules={[{ required: true }]}>
            <TextArea placeholder="请输入地址" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default User;
